//
//  LJYFlutterHomePlugin.swift
//  ljy_demo
//
//  Created by xiandao on 2025/9/3.
//

import Foundation
import Flutter

var homeFlutterChannel: FlutterMethodChannel?

class LJYFlutterHomePlugin: NSObject {
    // 唯一通道标识
    let BLE_CHANNEL_NAME = "flutter_home_plugin/methods"
    
    
    func register(controller: FlutterViewController) {

        homeFlutterChannel = FlutterMethodChannel(name: BLE_CHANNEL_NAME, binaryMessenger: controller.binaryMessenger)
        homeFlutterChannel?.setMethodCallHandler({call, result in
            
            print("方法名：\(call.method)")
            
            self.calculateArguments(arguments: call.arguments)
            
            result(990909)
        })
    }
    
    func calculateArguments(arguments: Any?) {
        if let dict = arguments as? Dictionary<String, Any> {
            let data = dict["data"] as? Int ?? -1
            let msg = dict["msg"] as? String ?? "假的"
            print("参数：data = \(data) msg = \(msg)")
            
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
                var dict = [String: Any]()
                dict.updateValue(10101001, forKey: "number")
                dict.updateValue("仙道是最棒的", forKey: "massage")
                dict.updateValue(true, forKey: "isTrue")
                
                if let chanel = homeFlutterChannel {
                    chanel.invokeMethod("returnMethod", arguments: self.dictToString(dict))
                }
            }
        }
    }
    
    // 字典转json
    func dictToString(_ dic:[String : Any]) -> String {
        let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
        let str = String(data: data!, encoding: String.Encoding.utf8)
        return str! as String
    }
}
